package com.cmlite.connect;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.util.Log;

import com.cmlite.model.OutResult;
import com.cmlite.util.ConnectionException;
import com.cmlite.util.Constant;
import com.cmlite.util.EmptyDataException;
import com.cmlite.util.TokenUnableException;



public class HTTPReq {
   private static final String TAG   = HTTPReq.class.getName();
    private static final String POST_METHOD = "POST";
    private static final String GET_METHOD = "GET";
    private static final String CHARSET = "Charset";
    private static final String UTF8 = "UTF-8";

	private String server_url;
    
	public HTTPReq() {
	}
	
	public HTTPReq(String svrurl) {
		server_url = svrurl;
	}
	private String createGetString(List<String> data)
	{
		
		StringBuilder strbuild = new StringBuilder();
		
		for (String key:data) {
			if (strbuild.length() != 1) {
				strbuild.append("/");
			}
			strbuild.append(key);
		}
		return strbuild.toString();
	}

	
	private String createPostString(Map<String,String> data)
	{
		Set<String> keys = data.keySet();
		StringBuilder strbuild = new StringBuilder();
		for (String key:keys) {
			if (strbuild.length() != 0) {
				strbuild.append("&");
			}
			strbuild.append(key);
			strbuild.append("=");
			strbuild.append(data.get(key));
		}
		return strbuild.toString();
	}
	private  List<NameValuePair> creatPostNameValue(Map<String,String> data){
		Set<String> keys = data.keySet();
		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
		for (String key:keys){
			 nameValuePairs.add(new BasicNameValuePair(key,data.get(key)));
		}
       return nameValuePairs;
	}
public String get(Context context,String method,List<String> data)
		  throws EmptyDataException, ConnectionException, JSONException, 
		         TokenUnableException {
		
		String out = "";
		try {
			
			DefaultHttpClient httpClient = new MyHttpClient(context);
			String param  = createGetString(data);
			final String url = server_url + method + param ;
			Log.d("GET" + method , url);
			HttpGet httpGet = new HttpGet(url);
			HttpParams httpParameters = new BasicHttpParams();
			HttpConnectionParams.setConnectionTimeout(httpParameters,Constant.CONNECT_TIMEOUT);
			HttpConnectionParams.setSoTimeout(httpParameters, Constant.CONNECT_TIMEOUT);
			httpClient.setParams(httpParameters);
			HttpResponse response = httpClient.execute(httpGet);
			BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
			   StringBuffer stringBuffer = new StringBuffer("");
			   String line = "";
			   String LineSeparator = System.getProperty("line.separator");
			   while ((line = bufferedReader.readLine()) != null) {
			    stringBuffer.append(line + LineSeparator); 
			   }
			   bufferedReader.close();
			   out = stringBuffer.toString();
			   Log.d("Response : " + method , out);
			   
	// check		   
		    if(out == null && out.length() <= 0){
			   throw new EmptyDataException();
		    }else{
		    	OutResult a  = prsBase(out);
		    	if(a.getCode() == OutResult.CODE_TOKEN){
		    		throw new TokenUnableException(a);
		    	}
		    }
		} catch (MalformedURLException e){
			throw new ConnectionException();
		} catch (IOException e){
			throw new ConnectionException();
		} 
		return out;
	}

	public String post(Context context,String method,Map<String, String> data) 
			throws EmptyDataException, ConnectionException, JSONException, 
                     TokenUnableException {
		
		String out = "";
		try {
			
			DefaultHttpClient httpClient = new MyHttpClient(context);
//			SSLSocketFactory sslSocketFactory = (SSLSocketFactory) httpClient
//		            .getConnectionManager().getSchemeRegistry().getScheme("https")
//		            .getSocketFactory();
//		    final X509HostnameVerifier delegate = sslSocketFactory.getHostnameVerifier();
//		    if(!(delegate instanceof MyVerifier)) {
//		        sslSocketFactory.setHostnameVerifier(new MyVerifier(delegate));
//		    }
			final String url = server_url + method;
			HttpPost httpPost = new HttpPost(url);
			
			Log.d(TAG,"Api : " + url);
			HttpParams httpParameters = new BasicHttpParams();
			HttpConnectionParams.setConnectionTimeout(httpParameters,Constant.CONNECT_TIMEOUT);
			HttpConnectionParams.setSoTimeout(httpParameters, Constant.CONNECT_TIMEOUT);
			
			httpPost.setParams(httpParameters);
			List<NameValuePair> listValueName  = creatPostNameValue(data);
			httpPost.setEntity(new UrlEncodedFormEntity(listValueName));
			HttpResponse response = httpClient.execute(httpPost);
			BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
			   StringBuffer stringBuffer = new StringBuffer("");
			   String line = "";
			   String LineSeparator = System.getProperty("line.separator");
			   while ((line = bufferedReader.readLine()) != null) {
			    stringBuffer.append(line + LineSeparator); 
			   }
			   bufferedReader.close();
			   out = stringBuffer.toString();
			   Log.d(TAG,"Response: " + out);
			// check		   
			    if(out == null ){
				   throw new EmptyDataException();
			    }else{
			    	OutResult a  = prsBase(out);
			    	if(a.getCode() == OutResult.CODE_TOKEN){
			    		throw new TokenUnableException(a);
			    	}
			    }
			} catch (MalformedURLException e){
				throw new ConnectionException();
			} catch (IOException e){
				throw new ConnectionException();
			} 
			return out;
	}
	public static void putString(Map<String,String> map, String key, String str) {

		if (key == null || str == null) {
			return;
		}
		map.put(key, str);
	}

	
	public static void putList(Map<String,String> map, String key, List<String> list) {

		
		if (key == null || list == null || list.isEmpty() || list.size() == 0) {
			return;
		}

		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < list.size(); i++) {
			if (i > 0) {
				sb.append(",");
			}
			sb.append(list.get(i));
		}
		map.put(key, sb.toString());
	}
	private OutResult prsBase(String json) throws JSONException{
		OutResult result = new OutResult();
		JSONObject c = new JSONObject(json);
		result.setCode(getString(c,OutResult.CODE));
		result.setStatus(getString(c,OutResult.STATUS));
		result.setMessage(getString(c,OutResult.MESSAGE));
		return result;
	}
	 private  String getString(JSONObject jsonObject,String name){
		  String tmp;
		try {
			tmp = jsonObject.isNull(name) ? "" : jsonObject.getString(name);
			 if(tmp == null )tmp ="";
		} catch (JSONException e) {
			tmp ="";
			e.printStackTrace();
		}
		 return tmp;
	  }

}
